const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const { JWT_SECRET } = require('../tool/middleWare')
const User = require('../model/User');
const Advisor = require('../model/Advisor');
const {isValidPhoneNumber, isValueInEnum} = require("../tool/function");
const {USER_TYPE,CONTRYCODE} = require("../model/other/enums");
const ApiError =require('../tool/utils/api_error')

async function login({ phoneNumber, countryCode, password, type }) {
    if (!isValidPhoneNumber(phoneNumber, countryCode) || !isValueInEnum(CONTRYCODE, countryCode)) {
        throw ApiError.BadRequest('手机号格式错误');
    }
    if (!isValueInEnum(USER_TYPE, type)) {
        throw ApiError.BadRequest('type 参数必须是 0 或 1');
    }
    //todo 检验密码

    // 根据 type 查询对应表
    let user;
    if (type === USER_TYPE.NORMAL) {
        user = await User.findOne({
            where: { phoneNumber },
            attributes: ['id', 'userName', 'phoneNumber', 'password']
        });
    } else if (type === USER_TYPE.ADVISOR) {
        user = await Advisor.findOne({
            where: { phoneNumber },
            attributes: ['id', 'userName', 'phoneNumber', 'password']
        });
    }

    if (!user) {
        throw ApiError.BadRequest('用户名或密码错误');
    }

    const match = await bcrypt.compare(password, user.password);
    if (!match) {
        throw ApiError.BadRequest('用户名或密码错误');
    }

    // 生成 payload 和 token
    const payload = user.toJSON();
    delete payload.password;
    payload.type = type;

    const token = jwt.sign(payload, JWT_SECRET, { expiresIn: '30d' });

    return { loginUser: payload, token };
}

module.exports = { login };